package com.deep.bilibili.security;


import com.deep.bilibili.dto.AdminerDto;
import com.deep.bilibili.dto.PermissionDto;
import com.deep.bilibili.dto.RoleDto;

import com.deep.bilibili.service.AdminerService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private AdminerService adminerService;

    /**
     * 授权的时候是对角色授权，而认证的时候应该基于资源，而不是角色，因为资源是不变的，而用户的角色是会变的
     */

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        AdminerDto adminerDto = adminerService.getUserByName(username);
        // 不存在
        if (!Optional.ofNullable(adminerDto).isPresent()) {
            throw new UsernameNotFoundException(username);
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (RoleDto roleDto : adminerDto.getRoles()) {
            for (PermissionDto permissionDto : roleDto.getPermissions()) {
                authorities.add(new SimpleGrantedAuthority(permissionDto.getCode()));
            }
        }

        return new User(adminerDto.getUsername(), adminerDto.getPassword(), authorities);
    }
}